#!/usr/bin/python

import socket
import time
from threading import Thread
import struct

def time_sync(data, addr):
    new_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    curr_time = time.time()
    new_sock.sendto(struct.pack('d', curr_time), (addr[0], addr[1]))
    new_sock.close()

HOST = ''                 # Symbolic name meaning all available interfaces
TS_PORT = 50008           # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

this_node_id = socket.gethostbyname(socket.gethostname())
print 'Node ip: ' + this_node_id
print 'Socket Created. Initializing...'
try:
    s.bind((HOST, TS_PORT))
except socket.error, msg:
    print 'Bind failed. Error code: ' + str(msg[0]) + ', Error message : ' + msg[1]
    sys.exit();

#s.listen(20)
print 'Socket bound on port: ' + str(TS_PORT)

#create threads to handle time sync
NUM_TS_THREADS = 5

#for i in range(NUM_TS_THREADS):
#     t = Thread(target=time_sync)
#     t.setDaemon(True)
#     t.start()

#hang out and listen for stuffs
while 1:
    data, addr = s.recvfrom(8)
    print 'Recieved from ', addr[0] + ':' + str(addr[1])
    #send time info
    t = Thread(target=time_sync, args=(data, addr))
    t.start()